package com.arvin.faceDetect.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(
    entities = [RecognitionRecord::class, FaceEntity::class],
    version = 3,
    exportSchema = false
)
@TypeConverters(Converters::class)
abstract class FaceDatabase : RoomDatabase() {
    abstract fun recognitionRecordDao(): RecognitionRecordDao
    abstract fun faceDao(): FaceDao

    companion object {
        @Volatile
        private var INSTANCE: FaceDatabase? = null

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE recognition_records ADD COLUMN faceBitmap BLOB")
            }
        }

        private val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 创建人脸表
                database.execSQL(
                    """
                    CREATE TABLE IF NOT EXISTS faces (
                        id TEXT NOT NULL PRIMARY KEY,
                        name TEXT NOT NULL,
                        faceImage BLOB NOT NULL,
                        faceFeatures TEXT NOT NULL,
                        createTime INTEGER NOT NULL DEFAULT ${System.currentTimeMillis()}
                    )
                """.trimIndent()
                )
            }
        }

        fun getDatabase(context: Context): FaceDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    FaceDatabase::class.java,
                    "face_database"
                )
                    .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}